package cn.stylefeng.guns.modular.filerun.service;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.modular.fileTag.service.FileTagService;
import cn.stylefeng.guns.modular.filerun.mapper.FileRunMapper;
import cn.stylefeng.guns.modular.filerun.model.FileParam;
import cn.stylefeng.guns.modular.filerun.model.FileResult;
import cn.stylefeng.guns.modular.filerun.uploadclient.FastDFSClient;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.modular.system.entity.FileImgPO;
import cn.stylefeng.guns.sys.modular.system.entity.FilePO;
import cn.stylefeng.guns.sys.modular.system.entity.FileTagPO;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class FileRunService extends ServiceImpl<FileRunMapper, FilePO> {

    @Resource
    private FileRunMapper fileRunMapper;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private FileImgService fileImgService;
    @Autowired
    private FileTagService fileTagService;

    /**
     * 新增项目信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void addFile(FilePO filePO) {
        if (ToolUtil.isOneEmpty(filePO, filePO.getfName(),filePO.getfCategory(), filePO.getfAbstracts(), filePO.getfTag(),filePO.getfUrl(),filePO.getfContent())) {
//        if (ToolUtil.isOneEmpty(filePO, filePO.getfName(), filePO.getfAbstracts(), filePO.getfContent(), filePO.getfCategory(), filePO.getfTag())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        filePO.setCreateUserId(LoginContextHolder.getContext().getUser().getId());
        filePO.setCreateUserName(LoginContextHolder.getContext().getUser().getName());
        filePO.setCreateTime(System.currentTimeMillis());

        int insert = fileRunMapper.insert(filePO);//插入主记录
        if (insert == 0) {
            throw new ServiceException(BizExceptionEnum.INSERT_FAILE);
        }
        fileRunMapper.updateById(filePO);
    }

    //标签转化
    private List<String> tagToList(Map<Long, String> tagMap, String tags) {
        if (!Strings.isNullOrEmpty(tags)) {
            List<String> stringList = new ArrayList<>();
            String[] split = tags.split(",");
            for (String s : split) {
                if (!Strings.isNullOrEmpty(s)) {
                    stringList.add(tagMap.get(Long.parseLong(s)).toString());
                }
            }
            return stringList;
        }
        return null;
    }

    //切割字符串
    private static String[] split2List(String str) {
        if (!StringUtils.isEmpty(str)) {
            return str.substring(0, str.length() - 1).split("_");
        }
        return null;
    }

    //fastdfs上传文件
    public String uploadFile(MultipartFile file) {
        try {
            return fastDFSClient.uploadFile(file);
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }

    //fastdfs删除文件
    public void deleteFile(String fileUrl) {
        try {
            fastDFSClient.deleteFile(fileUrl);
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    //修改和删除---先删除oss服务其上的图片，再删除数据库的连接
    public Integer mangeOss(FileParam fileParam) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("fid", fileParam.getFId());
        List<FileImgPO> fileImgPOS = fileImgService.listByMap(columnMap);
        //删除oss服务器数据
        List<String> imgUrls = fileImgPOS.stream().map(FileImgPO::getUrl).collect(Collectors.toList());
        List<Long> imgIds = fileImgPOS.stream().map(FileImgPO::getId).collect(Collectors.toList());
        Integer code = 1;
        boolean b = false;
        if (!CollectionUtils.isEmpty(imgUrls)) {
            code = fileImgService.removeFileByOss(imgUrls).getCode();
        }
        //获取数据库记录oss连接记录
        if (!CollectionUtils.isEmpty(imgIds)) {
            b = fileImgService.removeByIds(imgIds);
        }
        if (b && code == 0) {
            return 0;
        } else {
            return -1;
        }
    }


    //逻辑处理
    // ====================================================================================

    //修改业务数据
    public boolean updateRecord(FileParam fileParam) {
        //获取主记录数据
        FilePO filePO = this.getById(fileParam.getFId());
        if (!StringUtils.isEmpty(fileParam.getFUrl()) && !filePO.getfUrl().equals(fileParam.getFUrl())) {
            //链接相等不删除
            this.deleteFile(filePO.getfUrl());
        }
        //常规属性拷贝
        BeanUtils.copyProperties(fileParam, filePO);
        filePO.setfId(fileParam.getFId());
        filePO.setUpdateUserId(LoginContextHolder.getContext().getUser().getId());
        filePO.setUpdateUserName(LoginContextHolder.getContext().getUser().getName());
        filePO.setUpdateTime(System.currentTimeMillis());
        //插入修改后的主记录
        return this.updateById(filePO);
    }

    //调整数据
    public List<FileResult> processList(Page page,FileParam fileParam) {
        List<FilePO> list = fileRunMapper.list(page,fileParam.getCondition());
        List<FileResult> results = new ArrayList<>(list.size());
        if (!CollectionUtils.isEmpty(list)) {
            List<FileTagPO> tagList = fileTagService.list();
            Map<Long, String> tagnameMap = tagList.stream().collect(Collectors.toMap(FileTagPO::getId, FileTagPO::getTagName));
            list.forEach(filePO -> {
                FileResult fileResult = new FileResult();
                BeanUtils.copyProperties(filePO, fileResult);
                List<String> tagNameList = tagToList(tagnameMap, filePO.getfTag());
                if (!CollectionUtils.isEmpty(tagNameList)) {
                    fileResult.setfTag(String.join(",", tagNameList));
                }
                String tageName = tagnameMap.get(Long.parseLong(filePO.getfCategory()));
                if (!StringUtils.isEmpty(tageName)) {
                    fileResult.setfCategory(tageName);
                }
                fileResult.setShowCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(filePO.getCreateTime()));
                if (null != filePO.getUpdateTime()) {
                    fileResult.setShowUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(filePO.getUpdateTime()));
                }
                results.add(fileResult);
            });
        }

        return results;
    }

    //切割字符串
    private static String split2Str(String str) {
        if (!StringUtils.isEmpty(str)) {
            return str.substring(0, str.length() - 1);
        }
        return null;
    }
}


